react 装饰器报错怎么办-当前热议

来源:php中文网 | 2023-01-05 11:50:25 |

本教程操作环境:Windows10系统、react18.0.0版、Dell G3电脑

react 装饰器报错怎么办?

React的decorators装饰器报错


(资料图)

一、decorators装饰器报错@

在初次使用React 的装饰器时,第一次在项目中使用 @ 会报错,原因是react默认是不支持装饰器的,所以才会报错,所以是需要做一些配置来支持装饰器。

【报错显示:Parsing error: This experimental syntax requires enabling one of the following parser plugin(s): “decorators-legacy”, “decorators”.】

1. 创建项目

npm install -g create-react-app  // 安装create-react-app,已安装请忽略create-react-app mobx-study

2. 安装插件 —— 改变 create-react-app 中 webpack 配置

yarn add -D react-app-rewired customize-cra yarn add -D @babel/core @babel/plugin-proposal-decorators @babel/preset-env

3. 修改package.json文件中 scripts 脚本

// package.json"scripts": {    "start": "react-app-rewired start",    "build": "react-app-rewired build",    "test": "react-app-rewired test",    "eject": "react-scripts eject"  }

4. 在项目根目录下创建 config-overrides.js 并写入以下内容

const path = require("path")const { override, addDecoratorsLegacy } = require("customize-cra")function resolve(dir) {    return path.join(__dirname, dir)}const customize = () => (config, env) => {    config.resolve.alias["@"] = resolve("src")    if (env === "production") {        config.externals = {            "react": "React",            "react-dom": "ReactDOM"        }    }    return config};module.exports = override(addDecoratorsLegacy(), customize())

5. 在项目根目录下创建 .babelrc 并写入以下内容

{    "presets": [        "@babel/preset-env"    ],    "plugins": [        [            "@babel/plugin-proposal-decorators",            {                "legacy": true            }        ]    ]}

基本完成以上步骤就可以正常使用装饰器了,再也不会报 @ 的错误了。同时Support for the experimental syntax ‘decorators-legacy’ isn’t currently enabled这个错误也将消失。

二、对修饰器的实验支持功能在将来的版本中可能更改。在 “tsconfig” 或 “jsconfig” 中设置 “experimentalDecorators” 选项以删除此警告。ts(1219)

设置 => 搜索experimentalDecorators => 打上勾勾

推荐学习:《react视频教程》

以上就是react 装饰器报错怎么办的详细内容,更多请关注php中文网其它相关文章!

关键词: React